# ConfigManager.gd
#class_name ConfigManager extends Node
extends Node

enum CONFIG_TYPES {ENEMY, EQUIPMENT, LEVEL, PHOTO}
# 声明常量配置文件路径
const CONFIG_PATHS := {
	CONFIG_TYPES.ENEMY: "res://data/configs/enemies.csv",
	CONFIG_TYPES.EQUIPMENT: "res://data/configs/equipment.csv",
	CONFIG_TYPES.LEVEL: "res://data/configs/levels.csv",
	CONFIG_TYPES.PHOTO: "res://data/configs/photos.csv"
}
var _config_data := {
	CONFIG_TYPES.ENEMY: {},
	CONFIG_TYPES.EQUIPMENT: {},
	CONFIG_TYPES.LEVEL: {},
	CONFIG_TYPES.PHOTO: {}
}
# 新增：加载状态标志和完成信号
var is_loaded := false
var current_loading_type: CONFIG_TYPES  # 新增变量

func _ready() -> void:
	# 确保仅加载一次
	if not is_loaded:
		print("ConfigManager 实例路径：", get_path()) 
		await load_all_configs()
		is_loaded = true
		print("发送 config_loaded 信号")
		_EventBus.config_loaded.emit()
	print("ConfigManager._ready() 执行完毕")
	
func load_all_configs():
	print("开始加载所有配置...")
	for type in CONFIG_TYPES.values():
		_load_config(type,CONFIG_PATHS[type])
	print("所有配置加载完成！")
	
func _load_config(type: CONFIG_TYPES, path: String):
	print("正在加载配置：", type)
	print("完整路径：", ProjectSettings.globalize_path(path))
	current_loading_type = type  # 新增：记录当前解析类型
	var file = FileAccess.open(path, FileAccess.READ)
	if not file:
		var error = FileAccess.get_open_error()
		push_error("文件打开失败！错误码：%d - %s" % [error, error_string(error)])
		return
	
	var headers = file.get_csv_line()
	while not file.eof_reached():
		var line = file.get_csv_line()
		if line.size() != headers.size():
			continue
		
		var entry = {}
		for i in range(headers.size()):
			var key = headers[i].to_lower()
			entry[key] = _parse_value(line[i])
		
		var id_key = entry.get("id", "")
		if id_key:
			_config_data[type][id_key] = entry
	print("已加载配置类型：%s" % type)
	
func _parse_value(value: String) -> Variant:
	if value.begins_with("{") and value.ends_with("}"):
		return JSON.parse_string(value.replace('""', '"'))
	elif value.is_valid_int():
		return value.to_int()
	elif value.is_valid_float():
		return value.to_float()
	# 仅在处理敌人、照片、装备卡池时解析范围
	elif "-" in value and current_loading_type in [
		CONFIG_TYPES.ENEMY, 
		CONFIG_TYPES.PHOTO, 
		CONFIG_TYPES.EQUIPMENT
	]:
		return _parse_id_range(value)
	return value# LEVEL 配置的字段保持为原始字符串
	
static func _parse_id_range(value: String) -> Array:
	var parts = value.split("-")
	if parts.size() != 2:
		return []
	
	var start = parts[0].substr(1).to_int()
	var end = parts[1].substr(1).to_int()
	var prefix = parts[0][0]
	
	var result = []
	for i in range(start, end+1):
		result.append("%s%03d" % [prefix, i])
	return result
	
func get_config(type: CONFIG_TYPES, id: String) -> Dictionary:
	return _config_data.get(type, {}).get(id, {})
	
func get_config_pool(type: CONFIG_TYPES, ids: Variant) -> Array:
	if ids is String:
		ids = _parse_id_range(ids)
	
	var result = []
	for id in ids:
		if _config_data[type].has(id):
			result.append(_config_data[type][id])
	return result
	
#0330 add
func get_enemy_config(enemy_id: String) -> Dictionary:
	return _config_data[CONFIG_TYPES.ENEMY].get(enemy_id, {})

func get_photo_config(photo_id: String) -> Dictionary:
	return _config_data[CONFIG_TYPES.PHOTO].get(photo_id, {})

func get_equipment_config(equip_id: String) -> Dictionary:
	return _config_data[CONFIG_TYPES.EQUIPMENT].get(equip_id, {})

func get_level_config(level_id: String) -> Dictionary:
	return _config_data[CONFIG_TYPES.LEVEL].get(level_id, {})
	
func _push_file_error(type: CONFIG_TYPES, error: int) -> void:
	push_error("配置加载失败 [%s] 错误码：%d - %s" % [
		CONFIG_TYPES.keys()[type], 
		error, 
		error_string(error)
	])
